# -*-coding:utf-8-*-
import sqlite3
import pymysql
from typing import Iterable

"""
sqlite3的占位符为?
pymysql的占位符为%s
使用占位符时字符串和数值都不需要加引号
"""

class Manager(object):
    def __init__(self):
        self.connect = None
        self.cursor = None

    def execute_demo(self, sql, param: Iterable = None):
        # CREATE TABLE test(id integer PRIMARY KEY AUTOINCREMENT, name text(40) NOT NULL);
        if param is None:
            param = []
        self.cursor.execute(sql, param)

    def insert_one(self, sql, param: Iterable = None):
        # insert_one("insert into test(name) values(?)",['name'])
        # insert_one("insert into test(name) values(?)")
        if param is None:
            param = []
        self.cursor.execute(sql, param)
        return self.cursor.rowcount

    def insert_many(self, sql, param: Iterable[tuple]):
        #  insert_many("insert into test(name) values(?)", [('wangwu',), ('zaoliu',)])
        self.cursor.executemany(sql, param)
        return self.cursor.rowcount

    def query(self, sql, param: Iterable = None):
        if param is None:
            param = []
        self.cursor.execute(sql, param)
        return self.cursor.fetchall()

    def __enter__(self):
        return self.cursor

    def __exit__(self, exc_type, exc_val, exc_tb):
        self.connect.commit()
        self.cursor.close()
        self.connect.close()


class SqliteManager(Manager):
    def __init__(self, file_path):
        super().__init__()
        self.connect = sqlite3.connect(file_path)
        self.cursor = self.connect.cursor()

class MySqlManager(Manager):
    def __init__(self, user, passwd, db, host='localhost', port=3306):
        super().__init__()
        self.connect = pymysql.connect(user=user, password=passwd, host=host, database=db, port=port)
        self.cursor = self.connect.cursor()

if __name__ == '__main__':
    with SqliteManager('a.db3') as cursor:
        cursor.execute('select * from test')
        print(cursor.fetchall())
